package bist.believeinstep.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import bist.believeinstep.dao.ConnectionDAO;
import bist.believeinstep.dao.ImageDAO;
import bist.believeinstep.domain.Image;
import bist.believeinstep.mapper.ImageMapper;

public class ImageTemplate implements ImageDAO, ConnectionDAO {
	
	private JdbcTemplate jdbcTemplate;
	@Override
	public void setDataSource(DataSource dataSource){
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	@Override
	public void create(Image image){
		String query = "INSERT INTO bist_images (name, link, image, tag, type,"
				+ "created_date, modified_date, created_by, modified_by) VALUES (?,?,?,?,?,?,?,?,?)";
		try{
			jdbcTemplate.update(query, new Object[]{
				image.getName(),
				image.getLink(),
				image.getImage(),
				image.getTag(),
				image.getType(),
				image.getCreated(),
				image.getModified(),
				image.getCreatedBy(),
				image.getModifiedBy()
			});
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	@Override
	public void update(Image image){
		String query = "UPDATE bist_images SET"
				+ "name = ?"
				+ "link = ?"
				+ "image = ?"
				+ "tag = ?"
				+ "type = ?"
				+ "created_date = ?"
				+ "modified_date = ?"
				+ "created_by = ?"
				+ "modified_by = ?";
		try{
			jdbcTemplate.update(query, new Object[]{
				image.getName(),
				image.getLink(),
				image.getImage(),
				image.getTag(),
				image.getType(),
				image.getCreated(),
				image.getModified(),
				image.getCreatedBy(),
				image.getModifiedBy()
			});
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	@Override
	public void delete(Integer id){
		String query = "DELETE FROM bist_images WHERE id = ?";
		try{
			jdbcTemplate.update(query, new Object[]{id});
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	@Override
	public Image getImage(Integer id){
		String query = "SELECT FROM bist_images WHERE id = ?";
		try{
			Image image = jdbcTemplate.queryForObject(query, new Object[]{id}, new ImageMapper());
			return image;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	@Override
	public Image getImage(String name){
		String query = "SELECT FROM bist_images WHERE name = ?";
		try{
			Image image = jdbcTemplate.queryForObject(query, new Object[]{name}, new ImageMapper());
			return image;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	@Override
	public List<Image> list(){
		String query = "SELECT * FROM bist_images";
		try{
			List<Image> image = jdbcTemplate.query(query, new ImageMapper());
			return image;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
}

